"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : Compatibility
Case Name   : 对参数fields enclosed的值进行验证,部分测试点合理报错
Create At   : 2023/06/20
Owner       : c00603284
Description :
        1.创建表
        2.导入数据，不指定fields enclosed参数
        3.导入数据，参数fields enclosed与参数fields terminated的值相同
        4.导入数据，参数fields  terminated为#
        5.导入数据，文件数据中连续出现2个fields enclosed参数值
        6.导入数据，参数fields  terminated为非单字节字符
Expect      :
        1.成功
        2.成功
        3.成功
        4.成功
        5.成功
        6.合理报错
History     :
"""
import os
import unittest

from yat.test import Node

from testcase.COMPATIBILITY.GRAMMAR.LOAD. \
    Opengauss_Compatibility_Grammar_Load_Common import LoadData
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger


class LoadData0041(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)} start----')
        self.common = Common()
        self.load_data = LoadData()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.pri_user = Node('PrimaryDbUser')
        self.case_lable = 'load_data_0041'
        self.db_name = f'db_{self.case_lable}'
        self.t_name = f't_{self.case_lable}'
        self.file_path = os.path.join('/home', self.pri_user.ssh_user)

        text1 = '----创建数据文件；expect:创建成功----'
        self.log.info(text1)
        self.data1 = "2	'aaa'	12\n3	'bbb'	13\n" \
                     "4	'ccc'	12\n5	'ddd'	13"
        self.data2 = "21--a,aa--12"
        self.data3 = "30,#худ,ожн,иковテ,ス.ト#,#136#"
        self.data4 = "222xx阳光的xx456"
        self.data5 = "333xx乐乐乐xx789"
        res = self.load_data.create_data_file(self.pri_user, self.case_lable,
                                              self.data1, self.data2,
                                              self.data3, self.data4,
                                              self.data5)
        self.assertTrue(res, '执行失败:' + text1)

        text2 = '----创建兼容B库；expect:创建成功----'
        self.log.info(text2)
        res = self.load_data.create_b_db(self.pri_sh, self.db_name)
        self.assertTrue(res, '执行失败:' + text2)

    def test_load(self):
        text = '----step1：创建表；expect：建表成功----'
        self.log.info(text)
        cols = 'c_id int(11)primary key,c_name varchar(50),c_age int(11)'
        res = self.load_data.create_table(self.pri_sh, self.db_name,
                                          self.t_name, cols)
        self.assertTrue(res, '执行失败:' + text)

        text = '----step2：导入数据，不指定fields enclosed参数；expect：成功----'
        self.log.info(text)
        f_path = os.path.join(self.file_path, f'{self.case_lable}_1.txt')
        sql1 = f"load data infile '{f_path}' " \
            f"into table {self.t_name};" \
            f"select * from {self.t_name};"
        res1 = self.pri_sh.execut_db_sql(sql1, dbname=self.db_name)
        self.log.info(res1)
        rows, _ = self.common.parse_sql_query_res(res1)
        expect = [['2', "'aaa'", '12'], ['3', "'bbb'", '13'],
                  ['4', "'ccc'", '12'], ['5', "'ddd'", '13']]
        self.assertEqual(rows, expect, '执行失败' + text)

        text = '----step3：参数fields enclosed与参数fields terminated' \
               '的值相同；expect：合理报错----'
        self.log.info(text)
        f_path = os.path.join(self.file_path, f'{self.case_lable}_2.txt')
        res2 = self.load_data.load_data(self.pri_sh, self.db_name,
                                        self.t_name, f_path,
                                        into_type='', col_sep='-',
                                        col_end='-')
        emsg1 = 'ERROR:  delimiter cannot contain quote character'
        self.assertIn(emsg1, res2, '执行失败' + text)

        text = '----step4：导入数据，fields enclosed by参数值为#；expect：成功----'
        self.log.info(text)
        f_path = os.path.join(self.file_path, f'{self.case_lable}_3.txt')
        sql = f'''load data infile '{f_path}' into table {self.t_name}
            character set 'sql_ascii'
            fields terminated by ',' enclosed by '#';
            select * from {self.t_name};'''
        res3 = self.pri_sh.execut_db_sql(sql, dbname=self.db_name)
        self.log.info(res3)
        rows, _ = self.common.parse_sql_query_res(res3)
        expect = [['30', 'худ,ожн,иковテ,ス.ト', '136']]
        self.assertEqual(rows, expect, '执行失败' + text)

        text = '----step5：导入数据，文件数据中连续出现2个fields enclosed' \
               '参数值；expect：合理报错----'
        self.log.info(text)
        f_path = os.path.join(self.file_path, f'{self.case_lable}_4.txt')
        sql = f"""load data infile '{f_path}' into table {self.t_name}
            fields terminated by 'x' enclosed by '''';
            select * from {self.t_name};"""
        res4 = self.pri_sh.execut_db_sql(sql, dbname=self.db_name)
        self.log.info(res4)
        emsg2 = 'ERROR:  extra data after last expected column'
        self.assertIn(emsg2, res4, '执行失败' + text)

        text = '----step6：导入数据，fields enclosed by参数值为非单字节字符；' \
               'expect：合理报错----'
        self.log.info(text)
        f_path = os.path.join(self.file_path, f'{self.case_lable}_5.txt')
        res5 = self.load_data.load_data(self.pri_sh, self.db_name,
                                        self.t_name, f_path,
                                        into_type='', col_sep='x',
                                        col_end='xx')
        emsg3 = 'ERROR:  COPY quote must be a single one-byte character'
        self.assertIn(emsg3, res5, '执行失败' + text)

    def tearDown(self):
        self.log.info('----清理环境----')
        res = self.load_data.clear_env(self.pri_sh, self.pri_user,
                                       self.db_name,
                                       os.path.join(self.file_path,
                                                    f"{self.case_lable}*"))
        self.assertTrue(res, '执行失败:清理环境')
        self.log.info(f'----{os.path.basename(__file__)} end----')
